const redirectService = require('../services/redirectService');
const { pool } = require('../config/db');
const { getCurrentGroupOffset, getCurrentGroupId } = require('../utils/groupUtils');

const isMobile = (userAgent) => {
    return /mobile|iphone|ipad|android/i.test(userAgent.toLowerCase());
};


exports.handleRedirect = async (req, res) => {
    const { link } = req.params;
    const userAgent = req.headers['user-agent'];

    try {
        if (isMobile(userAgent)) {
            const targetUrl = await redirectService.resolveTargetUrl(link);
            if (targetUrl) {
                // return res.redirect(targetUrl);
                return res.json({code: 0, data: targetUrl});
            } else {
                return res.status(404).send('Link not found.');
            }
        } else {
            return res.json({code: 1, data: '请使用手机访问'})
        }
        
    } catch (err) {
        console.error(err);
        return res.status(500).send('Server error.');
    }
};

exports.getCurrentGroup = async (req, res) => {
    const conn = await pool.getConnection();
    try {
        // 获取 system_status
        const [[status]] = await conn.query('SELECT * FROM system_status WHERE id = 1');

        // 获取所有启用的分组
        const [enabledGroups] = await conn.query('SELECT id, group_name, sort_order FROM redirect_groups WHERE is_enabled = TRUE ORDER BY sort_order');
        if (enabledGroups.length === 0) {
            return res.status(404).json({ message: '没有找到启用的分组信息' });
        }

        // 计算当前分组索引
        const groupIndex = getCurrentGroupOffset(status.visit_count, status.threshold, enabledGroups);
        const currentGroup = enabledGroups[groupIndex];

        return res.json({
            currentGroup,
            visitCount: status.visit_count,
            yesterdayVisitCount: status.yesterday_visit,
            threshold: status.threshold,
            totalGroups: enabledGroups.length,
            enabledGroups: enabledGroups
        });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: '服务器错误' });
    } finally {
        conn.release();
    }
};
